package com.kele.controller;

import com.kele.domain.User;
import com.kele.service.UserService;
import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import java.util.Properties;

/**
 * @author 赵奥林
 * @date 2021年05月29日 15:09
 * @Description
 */

@Controller
@RequestMapping("/email")
public class emailController {

    static String stringBuilder ="";

    @Resource
    private UserService userService;

    @RequestMapping("/sendEmail")
    public void sendEmail(String qqEmail) throws Exception {
        emailController.mailUtil(qqEmail);
    }


    /**
     * 使用邮箱验证注册账号
     * @param qqEmail
     * @param password
     * @param rePassword
     * @return 截取邮箱字串中@前的字符串为账号 并验证验证码是否正确
     */
    @RequestMapping("/emailRegister")
    public String emailRegister(String qqEmail,
                                String password,
                                String rePassword,
                                String emailCode ,
                                HttpSession session,
                                ModelAndView modelAndView) throws Exception {
        emailController.mailUtil(qqEmail);
        String error ="";
        if (stringBuilder==""){
            //将验证码存到session中，并设置session有效期为60s
            session.setAttribute("eCode",stringBuilder);
            session.setMaxInactiveInterval(60);
            if (emailCode.equals(stringBuilder)){
                String account=qqEmail.substring(0,qqEmail.indexOf("@"));
                if (password.equals(rePassword)) {
                    User user = new User();
                    user.setAccount(account);
                    user.setPassword(password);
                    user.setEmail(qqEmail);
                    userService.insertUser(user);
                    return "static_resources/templates/login";
                }else{
                   error= "两次密码输入不一致";
                }
            }else{
               error="验证码错误";
            }
        }else{
           error="验证码发送失败";
        }
        modelAndView.addObject("error",error);
        return error;
    }

    /**
     * 邮箱验证码登录
     * @param qqEmail
     * @param emailCode
     * @param session
     * @param modelAndView
     * @return  邮箱验证码登录，登陆后和账号登陆一样
     */
    @RequestMapping("/emailLogin")
    public String emailLogin(      String qqEmail,
                                   String emailCode,
                                   HttpSession session,
                                   ModelAndView modelAndView) throws Exception {
        //emailController.mailUtil(qqEmail);
        String error="";
        if (stringBuilder==""){
            //将验证码存到session中，并设置session有效期为60s
            session.setAttribute("eCode",stringBuilder);
            session.setMaxInactiveInterval(60);
            if (emailCode.equals(stringBuilder)){
                String account = qqEmail.substring(0, qqEmail.indexOf("@"));
                String password = userService.queryPasswordByAccount(account);
                User user = userService.loginUser(account, password);
                if (user!=null){
                    session.setAttribute("user",user);
                    return "index";
                }else {
                    error="用户名不存在";
                }
            }else {
                error="验证码错误";
            }
        }else {
            error="验证码发送失败";
        }
        modelAndView.addObject("error",error);
        return error;
    }



    /**
     * 配置邮箱服务
     * @param toEmail
     * @throws Exception
     */
    public static void mailUtil(String toEmail) throws Exception {
        Properties prop = new Properties();
        // 开启debug调试，以便在控制台查看
        prop.setProperty("mail.debug", "true");
        // 设置邮件服务器主机名
        prop.setProperty("mail.host", "smtp.qq.com");
        // 发送服务器需要身份验证
        prop.setProperty("mail.smtp.auth", "true");
        // 发送邮件协议名称
        prop.setProperty("mail.transport.protocol", "smtp");
        // 开启SSL加密，否则会失败
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);
        // 创建session
        Session session = Session.getInstance(prop);
        // 通过session得到transport对象
        Transport ts = session.getTransport();
        // 连接邮件服务器：邮箱类型，帐号，POP3/SMTP协议授权码 163使用：smtp.163.com
        ts.connect("smtp.qq.com", "3189137314", "lfqymuctjywrdcef");
        // 创建邮件
        Message message = createSimpleMail(session,toEmail);
        // 发送邮件
        ts.sendMessage(message, message.getAllRecipients());

        ts.close();
    }

    /**
     * @Method: createSimpleMail
     * @Description: 创建一封只包含文本以及随机验证码的邮件
     */
    public static MimeMessage createSimpleMail(Session session, String toEmail) throws Exception {
        //  获取6为随机验证码
        String[] letters = new String[] {"0","1","2","3","4","5","6","7","8","9"};
        //随机生成六位验证码
        for (int i = 0; i < 6; i++) {
            stringBuilder = stringBuilder + letters[(int)Math.floor(Math.random()*letters.length)];
        }
        System.out.println(stringBuilder);
        // 创建邮件对象
        MimeMessage message = new MimeMessage(session);
        // 指明邮件的发件人
        message.setFrom(new InternetAddress("3189137314@qq.com"));
        // 指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
        // 邮件的标题
        message.setSubject("可乐验证");
        // 邮件的文本内容
        message.setContent("欢迎您使用【可乐】,账号注册验证码为(一分钟有效):"+stringBuilder+",请勿回复此邮件。", "text/html;charset=UTF-8");
        // 返回创建好的邮件对象
        return message;
    }


}
